<template>
  <div class="cart">
    <div class="container">
      <!-- 购物车头部 -->
      <div class="cart-header">
        <h2>我的购物车</h2>
        <div class="cart-summary">
          共 <span class="highlight">{{ totalItems }}</span> 件商品
        </div>
      </div>

      <!-- 购物车主体 -->
      <div class="cart-main" v-if="cartItems.length > 0">
        <!-- 表头 -->
        <div class="cart-table-header">
          <!-- 表头全选框 -->
          <div class="col-checkbox">
            <input 
              type="checkbox" 
              v-model="isAllSelected"
              @change="toggleSelectAll"
            >
          </div>
          <div class="col-info">商品信息</div>
          <div class="col-price">单价</div>
          <div class="col-quantity">数量</div>
          <div class="col-total">小计</div>
          <div class="col-action">操作</div>
        </div>

        <!-- 购物车列表 -->
        <div class="cart-list" v-loading="cartLoading">
          <div v-for="item in cartItems" :key="item.id" 
               class="cart-item" 
               :class="{ highlighted: item.highlighted }">
            <!-- 单个商品勾选框 -->
            <div class="col-checkbox">
              <input 
                type="checkbox" 
                v-model="item.selected"
                @change="updateSelection"
              >
            </div>
            <!-- 商品信息 -->
            <div class="col-info">
              <img :src="item.spuVO.mainImage" :alt="item.spuVO.title" style="width:80px;height:80px;object-fit:cover;">
              <div class="item-info">
                <h3>{{ item.spuVO.title }}</h3>
                <p class="desc">{{ item.spuVO.description }}</p>
                <div class="sku-specs">
                  <span v-for="(val, key) in item.skuSpecs" :key="key" class="sku-spec">
                    {{ key }}：{{ val }}
                  </span>
                </div>
              </div>
            </div>
            <!-- 单价 -->
            <div class="col-price">￥{{ item.promotionPrice }}</div>
            <!-- 数量 -->
            <div class="col-quantity">
              <el-input-number
                v-model="item.number"
                :min="1"
                :max="item.stockSnapshot || 99"
                @change="updateQuantity(item)"
                size="small"
                style="width: 100px;"
              />
            </div>
            <!-- 小计 -->
            <div class="col-total">￥{{ (item.promotionPrice * item.number).toFixed(2) }}</div>
            <!-- 操作 -->
            <div class="col-action">
              <button @click="removeItem(item)">删除</button>
            </div>
          </div>
        </div>

        <!-- 购物车底部 -->
        <div class="cart-footer">
          <!-- 底部全选框 -->
          <div class="left">
            <input 
              type="checkbox" 
              v-model="isAllSelected"
              @change="toggleSelectAll"
            > 全选
            <button class="remove-selected" @click="removeSelected">删除选中商品</button>
          </div>
          <div class="right">
            <div class="total-info">
              已选择 <span class="highlight">{{ selectedCount }}</span> 件商品
              合计：<span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <button class="checkout-btn" @click="checkout">结算</button>
          </div>
        </div>
      </div>

      <!-- 空购物车 -->
      <div v-else class="empty-cart">
        <el-empty
          description="购物车还是空的，去逛逛吧~"
        >
          <template #default>
            <router-link to="/" class="go-shopping">
              <el-button type="primary">去购物</el-button>
            </router-link>
          </template>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'  // 添加ElLoading
import { ElInputNumber } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'  // 添加Loading图标

const router = useRouter()
const route = useRoute()

// 购物车数据
const cartItems = ref([])
const cartLoading = ref(false) // 添加购物车加载状态
const highlightedItemId = ref(null) // 存储需要高亮的商品ID

// 计算属性
const totalItems = computed(() => cartItems.value.length)
const selectedCount = computed(() => cartItems.value.filter(item => item.selected).length)
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return item.selected ? total + (item.promotionPrice * item.number) : total
  }, 0)
})

// 全选状态的计算属性
const isAllSelected = computed({
  get: () => {
    // 当购物车为空时返回false
    if (cartItems.value.length === 0) return false
    // 所有商品都被选中时返回true
    return cartItems.value.every(item => item.selected)
  },
  set: (value) => {
    // 设置所有商品的选中状态
    cartItems.value.forEach(item => item.selected = value)
  }
})

// 更新选中状态
const updateSelection = () => {
  // 这里不需要额外操作，因为v-model已经更新了item.selected
  // 可以添加其他逻辑，如更新后端状态等
}

// 全选/取消全选的方法
const toggleSelectAll = () => {
  // v-model双向绑定已经处理了状态更新
  // 这里可以添加其他逻辑，如更新后端状态等
}

// 导入购物车相关接口
import { 
  getCartList, 
  deleteFromCart, 
  deleteCartList, 
  updateCartNumber 
} from '@/api/cart'

// 获取购物车列表
const fetchCartList = async () => {
  const uid = getUserId()
  if (!uid) {
    router.push({
      path: '/login',
      query: {
        redirect: '/cart'
      }
    })
    return
  }

  try {
    cartLoading.value = true // 设置加载状态
    
    // 获取highlight参数
    const highlightId = route.query.highlight
    highlightedItemId.value = highlightId ? String(highlightId) : null
    
    const response = await getCartList()
    
    // 处理购物车数据
    cartItems.value = response.map(item => {
      // 默认所有商品都不选中，只有匹配highlight的商品才选中
      const isHighlighted = highlightId && 
        (String(item.id) === String(highlightId) || 
         String(item.skuDTO?.id) === String(highlightId))
      
      return {
        ...item,
        selected: highlightId ? isHighlighted : (item.selected ?? true), // 有highlight参数时，只选中匹配的商品
        number: item.quantity,
        skuSpecs: item.skuDTO && item.skuDTO.specs
          ? JSON.parse(item.skuDTO.specs)
          : {},
        highlighted: isHighlighted // 添加高亮标记
      }
    })
    
    // 如果有高亮商品，滚动到该商品位置
    if (highlightId) {
      nextTick(() => {
        const highlightedItem = document.querySelector('.cart-item.highlighted')
        if (highlightedItem) {
          highlightedItem.scrollIntoView({ behavior: 'smooth', block: 'center' })
        }
      })
    }
  } catch (error) {
    console.error('获取购物车列表失败:', error)
    ElMessage.error(`获取购物车列表失败: ${error.message || '未知错误'}`)
  } finally {
    cartLoading.value = false // 无论成功失败都关闭加载状态
  }
}

// 更新商品数量
const updateQuantity = async (item) => {
  const uid = getUserId()
  if (!uid) {
    router.push({
      path: '/login',
      query: { redirect: '/cart' }
    })
    return
  }

  try {
    await updateCartNumber(item.id, item.number)  // 请求拦截器会自动添加uid
    ElMessage.success('更新数量成功')
  } catch (error) {
    ElMessage.error('更新数量失败')
    await fetchCartList()
  }
}

// 删除单个商品
const removeItem = async (item) => {
  const uid = getUserId()
  if (!uid) {
    router.push({
      path: '/login',
      query: { redirect: '/cart' }
    })
    return
  }

  try {
    if (confirm('确定要删除该商品吗？')) {
      await deleteFromCart(item.id)  // 请求拦截器会自动添加uid
      ElMessage.success('删除成功')
      await fetchCartList()
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 删除选中商品
const removeSelected = async () => {
  const uid = getUserId()
  if (!uid) {
    router.push({
      path: '/login',
      query: { redirect: '/cart' }
    })
    return
  }

  try {
    if (confirm('确定要删除选中的商品吗？')) {
      const selectedIds = cartItems.value
        .filter(item => item.selected)
        .map(item => item.id)
      
      if (selectedIds.length === 0) {
        ElMessage.warning('请选择要删除的商品')
        return
      }
      
      await deleteCartList(uid, selectedIds)  // 这里需要传递uid参数
      ElMessage.success('删除成功')
      await fetchCartList()
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 在组件挂载时获取购物车列表
onMounted(() => {
  fetchCartList()
})

const checkout = () => {
  const selectedItems = cartItems.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }

  // 构造结算商品数据
  const checkoutItems = selectedItems.map(item => ({
    id: item.id,
    pid: item.spuId,
    name: item.spuVO.title,
    image: item.spuVO.mainImage,
    price: item.promotionPrice,
    quantity: item.number,
    skuSpecs: item.skuSpecs,
    shopId: item.spuVO.shopId || null // 添加商店ID
  }))

  // 使用路由传递商品数据
  router.push({
    path: '/checkout',
    query: {
      items: encodeURIComponent(JSON.stringify(checkoutItems))
    }
  })
}
// 获取用户ID
const getUserId = () => {
  const idCookie = document.cookie.split(';').find(item => item.trim().startsWith('id='))
  if (!idCookie) return null
  const id = idCookie.split('=')[1].trim()
  // 确保返回的是数字类型
  return id ? parseInt(id) : null
}

</script>

<style scoped>
.cart {
  padding: 20px 0;
  background-color: var(--bg-color-page);
}

.container {
  width: 1200px;
  margin: 0 auto;
}

/* 购物车头部 */
.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.highlight {
  color: var(--primary-color);
  font-weight: bold;
}

/* 购物车表格样式 */
.cart-table-header {
  display: grid;
  grid-template-columns: 60px 400px 150px 150px 150px 100px;
  padding: 15px;
  background: var(--bg-color);
  border-radius: 4px;
  margin-bottom: 10px;
}

.cart-item {
  display: grid;
  grid-template-columns: 60px 400px 150px 150px 150px 100px;
  padding: 20px 15px;
  background: var(--bg-color);
  border-radius: 4px;
  margin-bottom: 10px;
  align-items: center;
}

/* 商品信息样式 */
.col-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.col-info img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.item-info h3 {
  margin: 0 0 5px;
  font-size: 14px;
}

.desc {
  color: #888;
  font-size: 13px;
  margin: 2px 0;
}

.sku-specs {
  margin-top: 4px;
  color: #888;
  font-size: 13px;
}

.sku-spec {
  margin-right: 12px;
}

/* 数量控制器样式 */
.quantity-control {
  display: flex;
  align-items: center;
  width: fit-content;
}

.quantity-control button {
  width: 28px;
  height: 28px;
  border: 1px solid var(--border-color);
  background: var(--bg-color);
  cursor: pointer;
}

.quantity-control input {
  width: 50px;
  height: 28px;
  text-align: center;
  border: 1px solid var(--border-color);
  border-left: none;
  border-right: none;
}

/* 购物车底部样式 */
.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: var(--bg-color);
  border-radius: 4px;
  margin-top: 20px;
}

.remove-selected {
  margin-left: 20px;
  padding: 5px 15px;
  border: 1px solid var(--border-color);
  background: var(--bg-color);
  cursor: pointer;
}

.total-price {
  color: var(--danger-color);
  font-size: 20px;
  font-weight: bold;
  margin: 0 10px;
}

.checkout-btn {
  padding: 10px 40px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 20px;
}

/* 空购物车样式 */
.empty-cart {
  text-align: center;
  padding: 50px 0;
  background: #fff;
  border-radius: 4px;
}

.go-shopping {
  text-decoration: none;
  margin-top: 20px;
  display: inline-block;
}

/* 高亮样式 */
.cart-item.highlighted {
  background: #fff8f0;
  border-left: 3px solid var(--primary-color);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  animation: highlight-pulse 2s ease-in-out;
}

@keyframes highlight-pulse {
  0% { background-color: #fff8f0; }
  50% { background-color: #fff0e0; }
  100% { background-color: #fff8f0; }
}
</style>
